<script setup lang="ts">
import {
    useReformInstallationApplyMerge,
    useReformInstallationProjectUnitList,
} from "@fl/api/elevator-api";
import { useGetCascadeData } from "@fl/api/elevator-api/verify";
import { SearchTable } from "@fl/components";
import { useMessage } from "@fl/hooks/web/use-message"; // 确认框
import { useUserStoreWithOut } from "@fl/store/modules/user";
import dayjs from "dayjs";
import { cloneDeep } from "lodash-es";
const userStore = useUserStoreWithOut();
const areaCode = userStore.getOrgInfo?.areaCode ?? "";
const isZone = ref<boolean>(areaCode === "429006000000");
const { createConfirmModal } = useMessage();
const props = withDefaults(
    defineProps<{
        initMergeList?: any;
    }>(),
    {
        initMergeList: () => [],
    }
);
const { initMergeList } = toRefs(props);
const gridRef = ref();
const show = defineModel("show");
const mergeList = ref(cloneDeep(initMergeList.value));
const mergeOptions = reactive<VxeGridProps>({
    minHeight: 300,
    columns: [
        { type: "radio", width: 50, slots: { header: "radioHeader" } },
        { field: "applyNo", title: "编号" },
        { field: "areaName", title: "所在区" },
        { field: "streetName", title: "街道" },
        { field: "communityName", title: "社区" },
        { field: "projectName", title: "小区" },
        {
            field: "building",
            title: "栋",
            editRender: {},
            slots: { default: "edit_building" },
        },
        {
            field: "unit",
            title: "单元",
            editRender: {},
            slots: { default: "edit_unit" },
        },
        { field: "status", slots: { default: "status" }, title: "审核状态" },
    ],
    editConfig: {
        mode: "cell",
        trigger: "click",
        beforeEditMethod({ row, rowIndex, column, columnIndex }) {
            if (row.id == selectRow.id) {
                return true;
            } else {
                return false;
            }
        },
    },
});
const getBuildingOptionsParams = ref({
    projectId: "",
    targetLabel: "building",
});
const getUnitOptionsParams = ref({
    buildingId: "",
});
const { data: buildingOptions } = useGetCascadeData(
    getBuildingOptionsParams,
    "projectId"
);
const { data: unitOptions } = useReformInstallationProjectUnitList(getUnitOptionsParams);
function isMoreThanThreeMonthsAgo(date) {
    // 上报时间超过三个月未处理需要标红
    const threeMonthAgo = dayjs().subtract(3, "month");
    return dayjs(date).isBefore(threeMonthAgo);
}
function mergeClose() {
    show.value = false;
    selectRow.value = {
        id: "",
    };
    initialRow.value = {
        id: "",
    };
}
const selectRow = ref({
    id: "",
});
const initialRow = ref({
    id: "",
});
const radioChangeEvent = ({ row }) => {
    selectRow.value = row;
    initialRow.value = cloneDeep(row);
    getBuildingOptionsParams.value.projectId = row.projectId;
    getUnitOptionsParams.value.buildingId = row.buildingId;
};
function clearRadioRowEvent() {
    const $grid = gridRef.value?.tableInstance;
    $grid.clearRadioRow();
    selectRow.value = { id: "" };
}
function buildingChange() {
    console.log("buildingOptions", buildingOptions.value);
    getUnitOptionsParams.value.buildingId =
        buildingOptions.value.find((v: any) => v.label === selectRow.value.building)
            ?.buildingId || "";
}
const { isPending, mutate } = useReformInstallationApplyMerge();
function mergeConfirm() {
    if (!selectRow.value.id) {
        ElMessage.warning("请选择合并保留记录");
        return;
    }
    const status = mergeList.value.map((item) => item.status);
    if (status.includes(20) && status.includes(300) && selectRow.value.status == 20) {
        ElMessage.warning("上报需求已处理无法被合并!");
        return;
    }
    if (isZone.value) {
        // 天门专区目前没有维护楼栋单元清册数据，只需要判断不为空即可
        if (!selectRow.value.building || !selectRow.value.unit) {
            ElMessage.warning("请输入楼栋单元");
            return;
        }
    } else {
        // 需判断楼栋单元是否在清册数据内
        if (
            !!!buildingOptions.value.find(
                (item) => item.value == selectRow.value.building
            ) ||
            !!!unitOptions.value.find((item) => item.unit == selectRow.value.unit)
        ) {
            ElMessage.warning("该楼栋/单元不存在于小区清册中，请重新选择");
            return;
        }
    }
    const ids = mergeList.value.map((item) => item.id);
    let params = {
        building: selectRow.value.building,
        projectId: selectRow.value.projectId,
        sourceUnit: ids.filter((item) => item != selectRow.value.id),
        targetUnit: selectRow.value.id,
        unit: String(selectRow.value.unit),
    };
    createConfirmModal({
        title: "提示",
        content: "合并后，数据无法撤回，是否确认？",
        onSuccess: () => {
            mutate(params, {
                onSuccess: () => {
                    ElMessage.success("操作成功");
                    mergeClose();
                },
            });
        },
    });
}
function buildingBlur() {
    const pattern = /^[A-Za-z0-9]+$/;
    if (!pattern.test(selectRow.value.building)) {
        selectRow.value.building = "";
    }
}
function buildinInput() {
    const pattern = /^[A-Za-z0-9]+$/;
    if (!pattern.test(selectRow.value.building)) {
        ElMessage.warning("楼栋只能包含字母或者数字");
    }
}

function unitBlur() {
    const pattern = /^(无|[a-zA-Z0-9]+)$/;
    if (!pattern.test(selectRow.value.unit)) {
        selectRow.value.unit = "";
    }
}
function unitInput() {
    const pattern = /^(无|[a-zA-Z0-9]+)$/;
    if (!pattern.test(selectRow.value.unit)) {
        ElMessage.warning("单元只能包含字母或者数字或'无'");
    }
}
</script>

<template>
    <ElDialog v-model="show" title="数据合并" width="70%" :destroy-on-close="true">
        <div style="height: 60vh; overflow: auto">
            <div>
                共{{ mergeList.length }}条记录需合并，<span style="color: #da0004"
                    >请选择合并保留记录</span
                >
            </div>
            <SearchTable
                ref="gridRef"
                v-bind="mergeOptions"
                :data="mergeList"
                @radio-change="radioChangeEvent"
            >
                <template #radioHeader>
                    <vxe-button
                        mode="text"
                        @click="clearRadioRowEvent"
                        :disabled="!!!selectRow.id"
                        >取消</vxe-button
                    >
                </template>
                <template #edit_building="{ row }">
                    <template v-if="row.id === selectRow.id">
                        <template v-if="isZone">
                            <!-- 专区暂时未维护楼栋单元清册数据，所以需要改成输入框填写 -->
                            <el-input
                                v-model="selectRow.building"
                                @blur="buildingBlur"
                                @input="buildinInput"
                            ></el-input>
                        </template>
                        <template v-else>
                            <el-select
                                v-model="selectRow.building"
                                @change="buildingChange()"
                            >
                                <el-option
                                    v-for="item in buildingOptions"
                                    :label="item.label"
                                    :value="item.value"
                                    :key="item.value"
                                />
                            </el-select>
                        </template>
                    </template>
                    <span v-else>{{ row.building }}</span>
                </template>
                <template #edit_unit="{ row }">
                    <template v-if="row.id === selectRow.id">
                        <template v-if="isZone">
                            <el-input
                                v-model="selectRow.unit"
                                @blur="unitBlur"
                                @input="unitInput"
                            ></el-input>
                        </template>
                        <template v-else>
                            <el-select v-model="selectRow.unit">
                                <el-option
                                    v-for="item in unitOptions"
                                    :label="item.unit"
                                    :value="item.unit"
                                    :key="item.unit"
                                />
                            </el-select>
                        </template>
                    </template>
                    <span v-else>{{ row.unit }}</span>
                </template>
                <template #status="{ row }">
                    <span
                        :class="
                            row.status === 20 && isMoreThanThreeMonthsAgo(row.createTime)
                                ? 'color-red'
                                : ''
                        "
                    >
                        {{
                            row.status === 20
                                ? "待处理"
                                : row.status === 300
                                ? "已满足表决要求"
                                : "暂不满足表决要求"
                        }}</span
                    >
                </template>
            </SearchTable>
            <ul style="color: #da0004">
                <li>注意事项：</li>
                <li>1.被合并记录，审核状态必须为“待处理”</li>
                <li>
                    2.当拟合并的多条记录中同时包含“待处理”和“已满足表决要求”记录时，必须以“已满足表决要求”记录为基准，进行保留。
                </li>
                <li>
                    3.在合并不同楼栋或单元的记录时，请选择最标准的楼栋、单元记录进行保留，或将楼栋、单元信息修改为最标准的。
                </li>
            </ul>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <ElButton @click="mergeClose"> 取消 </ElButton>

                <ElButton type="primary" @click="mergeConfirm" :loading="isPending">
                    确认
                </ElButton>
            </div>
        </template>
    </ElDialog>
</template>
